define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefined, Backend, Table, Form) {

    var Controller = {
        index: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'inventory/wmskc/index' + location.search,
                    add_url: 'inventory/wmskc/add',
                    edit_url: 'inventory/wmskc/edit',
                    del_url: 'inventory/wmskc/del',
                    multi_url: 'inventory/wmskc/multi',
                    import_url: 'inventory/wmskc/import',
                    export_url:'inventory/wmskc/export',
                    table: 'wms_kc',
                }
            });

            var table = $("#table");
            
            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                fixedColumns: true,
                fixedRightNumber: 1,
                //exportTypes: ['xlsx','csv'],
               /* exportOptions: {
                    fileName: '库存明细' + Moment().format("YYYY-MM-DD"), // 原方法 定义生成的文件名
                    ignoreColumn: [0, 'operate'],// 原方法 默认跳过输出多选框和操作列
                    preventInjection: false,//注意这个参数，可以解决负数导出是前面带引号的问题
                    mso: {
                    		//fileFormat: 'xlsx',
                    		onMsoNumberFormat: function (cell, row, col) {
                            	 return (row > 0 && col == 0) ? '\\@' : '';//强制文本
                             }
                         }
                },*/
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('Id'),visible:false},
                       // {field: 'AutoID', title: __('Autoid')},
                        {field: 'warehouse_name', title: __('Warehouse_name'), operate: 'LIKE'},
                        {field: 'warehouse_number', title: __('Warehouse_number'), operate: 'LIKE'},
                        {field: 'shelves_name', title: __('Shelves_name'), operate: 'LIKE'},
                        {field: 'shelves_number', title: __('Shelves_number'), operate: 'LIKE'},
                        {field: 'inv_number', title: __('Inv_number'),operate: 'LIKE'},
                        {field: 'inv_name', title:__("Inv_name"),operate: 'LIKE'},
                        {field: 'inv_specification', title:__("Specification"),operate: 'LIKE'},
                        // {field: 'cFree1', title:"物料属性",operate: 'LIKE'},
                        //{field: 'cBatch', title: __('Cbatch'), operate: 'LIKE',operate: false},
                        {field: 'quantity', title: __('Quantity'), operate:'BETWEEN'},
                        {field: 'inv_unit', title:__("Inv_unit"),operate: 'LIKE',operate: 'LIKE'},
                        {field: 'store_quantity', title: __('Store_quantity'), operate:'BETWEEN'},
                        {field: 'inv_store_unit', title:__("Inv_store_unit"),operate: 'LIKE',operate: 'LIKE'},
                        {field: 'cBatch', title:__("cBatch"),operate: 'LIKE',operate: 'LIKE'},
                       // {field: 'dMdate', title: __('Dmdate'), operate:'RANGE', addclass:'datetimerange', autocomplete:false},
                       // {field: 'dVDate', title: __('Dvdate'), operate:'RANGE', addclass:'datetimerange', autocomplete:false},
                       // {field: 'iMassDate', title: __('Imassdate')},
                       // {field: 'dLastCheckDate', title: __('Dlastcheckdate'), operate:'RANGE', addclass:'datetimerange', autocomplete:false},
                       // {field: 'cCheckState', title: __('Ccheckstate'), operate: 'LIKE'},
                        //{field: 'createtime', title: __('Createtime'), operate:'RANGE', addclass:'datetimerange', autocomplete:false},
                        //{field: 'shelves.wh_type', title: __('Wh_type'), searchList: whTypeArrList, formatter: Table.api.formatter.normal,width:80},
                        {field: 'wh_type', title: __('Wh_type'), searchList: whTypeArrList, formatter: Table.api.formatter.normal,width:80},
                        {field: 'updatetime', title: __('Updatetime'), operate:'RANGE', addclass:'datetimerange', autocomplete:false},
                        //{field: 'operate', title: __('Operate'), table: table, events: Table.api.events.operate, formatter: Table.api.formatter.operate}
                    ]
                ]
            });

            
          //*************************** 自定义export开始
            var submitForm = function (ids, layero) {
              var options = table.bootstrapTable('getOptions');
              var columns = [];
              $.each(options.columns[0], function (i, j) {
                  if (j.field && !j.checkbox && j.visible && j.field != 'operate') {
                      columns.push(j.field);
                  }
              });
              var search = options.queryParams({});
              $("input[name=search]", layero).val(options.searchText);
              $("input[name=ids]", layero).val(ids);
              $("input[name=filter]", layero).val(search.filter);
              $("input[name=op]", layero).val(search.op);
              $("input[name=columns]", layero).val(columns.join(','));
              $("form", layero).submit();
          };
          
          $(document).on("click", ".btn-to-export", function () {
        	  var ids = Table.api.selectedids(table);
              var page = table.bootstrapTable('getData');
              var all = table.bootstrapTable('getOptions').totalRows;
              
              let la = Layer.confirm("请选择导出的选项<form action='" + Fast.api.fixurl($.fn.bootstrapTable.defaults.extend.export_url) + "' method='post' target='_blank'><input type='hidden' name='ids' value='' /><input type='hidden' name='filter' ><input type='hidden' name='op'><input type='hidden' name='search'><input type='hidden' name='columns'></form>", {
                  title: '导出数据',
                  // btn: ["选中项(" + ids.length + "条)", "本页(" + page.length + "条)", "全部(" + all + "条)"],
                  btn: ["全部(" + all + "条)","选中(" + ids.length + "条)"],
                  success: function (layero, index) {
                      $(".layui-layer-btn a", layero).addClass("layui-layer-btn0");
                  }
                  , yes: function (index, layero) {
                      // submitForm(ids.join(","), layero);
                      submitForm("all", layero);
                      layer.close(la);//关
                      return false;
                  }
                  ,
                  btn2: function (index, layero) {
                  	if(ids.join(",")==''){
                        	Toastr.error('请选中要导出的记录');
                        	return ;
                      }//.join(",")
                      submitForm(ids, layero);
                      layer.close(la);//关
                      return false;
                  }
                  ,
                  btn3: function (index, layero) {
                      console.log(layero);
                      submitForm("all", layero);
                      return false;
                  }
              })
          });
          //*************************** 自定义export结束

          $('#print-btn').click(function(){
            let list =  table.bootstrapTable('getSelections');
            if(list.length==0){
                return Toastr.error("请先选择要打印的记录");   
            }
            let ids_arr = []
            let cBatch_arr = []
            for(let i=0;i<list.length;i++){
                ids_arr.push(list[i].inv_id)
                cBatch_arr.push(list[i].cBatch)
            }
            Fast.api.open('information/inventory/print?inventory_id='+ids_arr.join(',')+'&cBatch='+cBatch_arr.join(','),'打印物料信息');
        })

            // 为表格绑定事件
            Table.api.bindevent(table);

            /*$('.btn-upload').click(function(){
                Fast.config.openArea = ['70%','70%'];
                Fast.api.open('inventory/wmskc/import','导入库存');
            })*/
            
            $(table).data("operate-edit", null); // 列表页面隐藏 .编辑operate-edit - 删除按钮operate-del
			
        },
        recyclebin: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    'dragsort_url': ''
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: 'inventory/kc/recyclebin' + location.search,
                pk: 'id',
                sortName: 'id',
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('Id')},
                        {
                            field: 'deletetime',
                            title: __('Deletetime'),
                            operate: 'RANGE',
                            addclass: 'datetimerange',
                            formatter: Table.api.formatter.datetime
                        },
                        {
                            field: 'operate',
                            width: '140px',
                            title: __('Operate'),
                            table: table,
                            events: Table.api.events.operate,
                            buttons: [
                                {
                                    name: 'Restore',
                                    text: __('Restore'),
                                    classname: 'btn btn-xs btn-info btn-ajax btn-restoreit',
                                    icon: 'fa fa-rotate-left',
                                    url: 'inventory/kc/restore',
                                    refresh: true
                                },
                                {
                                    name: 'Destroy',
                                    text: __('Destroy'),
                                    classname: 'btn btn-xs btn-danger btn-ajax btn-destroyit',
                                    icon: 'fa fa-times',
                                    url: 'inventory/kc/destroy',
                                    refresh: true
                                }
                            ],
                            formatter: Table.api.formatter.operate
                        }
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        import:function (){
            Controller.api.bindevent();
        },
        add: function () {
            Controller.api.bindevent();
        },
        edit: function () {
            $('#choose-shelves').click(function(){
                let house_id = $("#c-warehouse_id").val();
                top.Fast.api.open('information/shelves/choose?warehouse_id='+house_id,'选择货架或库区',{offset: 'r',callback:function(value){
                        $("#c-shelves_id,#c-shelves_name").val(value.id);
                        $("#c-shelves_name").selectPageRefresh();
                    }});
            })
            Controller.api.bindevent();
        },
        choose:function(){
            $('#choose_id').click(function(){
                let id =  Controller.api.selectedids(chooseTable);
                Fast.api.close(id);
            })
            Table.api.init({
                extend: {
                    'dragsort_url': ''
                }
            });

            var chooseTable = $('#chooseTable')

            chooseTable.bootstrapTable({
                url: "inventory/kc/choose" + location.search,
                pk: 'id',
                search:false,
                singleSelect:false,
                sortName: 'id',
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: 'id',visible:false},
                        {field: 'cInvCode', title: '物料编码', operate: 'LIKE'},
                        {field: 'name', title:"物料名称",operate: 'LIKE'},
                        {field: 'specification', title:"规格型号",operate: 'LIKE'},
                        {field: 'cFree1', title:"物料属性",operate: 'LIKE'},
                        {field: 'unit', title:"单位",operate: 'LIKE'},
                        {field: 'cBatch', title: __('Cbatch'), operate: 'LIKE'},
                        {field: 'iQuantity', title: __('Iquantity'), operate:'BETWEEN'},
                        {field: 'shname', title: '货架'},
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(chooseTable);

        },
        api: {
            selectedids: function (table, current) {
                var options = table.bootstrapTable('getOptions');
                //如果有设置翻页记忆模式
                if (!current && options.maintainSelected) {
                    return options.selectedIds;
                }
                return $.map(table.bootstrapTable('getSelections'), function (row) {
                    return row;
                });
            },
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"));
            }
        }
    };
    return Controller;
});
